package br.com.ufpr.sgp.util.session;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.Cookie;

import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.cycle.RequestCycle;

import br.com.sebrae.pr.sgp.entities.Usuario;
import br.com.sebrae.pr.sgp.services.UsuarioServiceRemote;
import br.com.ufpr.sgp.WicketApplication;

public class CustomSessionProvider {

	public static final int REMEMBER_ME_DURATION_IN_DAYS = 30;
	public static final String REMEMBER_ME_LOGIN_COOKIE = "loginCookie";
	public static final String REMEMBER_ME_PASSWORD_COOKIE = "passwordCookie";

	public CustomSessionProvider() {
	}

	public WebSession createNewSession(final Request request) {
		final CustomSession cs = new CustomSession(request);

		final Cookie nmeLoginCookie = WicketApplication.get()
				.getCookieService()
				.loadCookie(request, REMEMBER_ME_LOGIN_COOKIE);
		final Cookie passwordCookie = WicketApplication.get()
				.getCookieService()
				.loadCookie(request, REMEMBER_ME_PASSWORD_COOKIE);

		if (nmeLoginCookie != null && passwordCookie != null
				&& StringUtils.isNotBlank(nmeLoginCookie.getValue())
				&& StringUtils.isNotBlank(passwordCookie.getValue())) {
			try {
				UsuarioServiceRemote usuarioServiceRemote = (UsuarioServiceRemote) new InitialContext()
						.lookup("java:global/sgp-ear/sgp-ejb/UsuarioServiceImpl");

				final Usuario usu = usuarioServiceRemote
						.pesquisarPorLoginSenha(nmeLoginCookie.getValue(),
								passwordCookie.getValue());

				if (usu != null) {
					cs.setUsuario(usu);

				} else {
					WicketApplication
							.get()
							.getCookieService()
							.removeCookieIfPresent(request,
									RequestCycle.get().getResponse(),
									REMEMBER_ME_LOGIN_COOKIE);
					WicketApplication
							.get()
							.getCookieService()
							.removeCookieIfPresent(request,
									RequestCycle.get().getResponse(),
									REMEMBER_ME_PASSWORD_COOKIE);
				}
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return cs;
	}
}
